<?php
namespace frontend\controllers;

use Yii;
use common\models\Course;
use common\models\search\CourseSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\CourseClass;
use yii\data\Pagination;
use common\models\Mclass;
use common\models\User;

/**
 * CourseController implements the CRUD actions for Course model.
 */
class CourseController extends Controller
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => [
                        'POST'
                    ]
                ]
            ]
        ];
    }

    /**
     * Lists all Course models.
     * 
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new CourseSearch();
        $where = [];
        if (isset($_GET['class']))
            $where['CourseSearch']['cid'] = (int) $_GET['class'];
        if (isset($_GET['name']))
            $where['CourseSearch']['name'] = $_GET['name'];
        $dataProvider = $searchModel->search($where);
        $class = [];
        if (isset($_GET['class'])) {
            $class = CourseClass::findOne([
                'id' => $_GET['class']
            ]);
        }
        $pages = new Pagination([
            'defaultPageSize' => 24,
            'totalCount' => $dataProvider->query->count()
        ]);
        $data = $dataProvider->query->offset($pages->offset)
            ->limit($pages->limit)
            ->orderBy('ID desc')
            ->all();
        return $this->render('index', [
            'data' => $data,
            'class' => $class,
            'pages' => $pages
        ]);
    }

    /**
     * Displays a single Course model.
     * 
     * @param string $id            
     * @return mixed
     */
    public function actionView($id)
    {
        $model = Course::find()->where('id=' . $id)->one();
        $model->look += 1;
        $model->save([
            'look' => $model->look
        ]);
        $class = CourseClass::find()->select('id,name,hot')
            ->orderBy('hot desc')
            ->asArray()
            ->all();
        $class = array_column($class, 'name', 'id');
        if ($model->cid) {
            $new = Course::find()->orderBy('id desc')
                ->where('cid=' . $model->cid . ' and id!=' . $id)
                ->limit(5)
                ->all();
        }
        $uid = Yii::$app->user->id;
        $num = 0;
        if ($uid) {
            $num = Mclass::find()->where([
                'uid' => $uid,
                'cid' => $id
            ])->count();
        }
        $hot = Course::find()->where('id!=' . $id)
            ->orderBy('look desc')
            ->limit(5)
            ->all();
        return $this->render('view', [
            'model' => $model,
            'new' => $new,
            'class' => $class,
            'hot' => $hot,
            'num' => $num
        ]);
    }

    public function actionPay($id)
    {
        $model = Course::findOne($id);
        $uid = Yii::$app->user->id;
        if (! $uid) {
            echo json_encode([
                'status' => 2
            ]);
            return;
        }
        $flag = false;
        $str = '支付失败';
        $num = Mclass::find()->where([
            'uid' => $uid,
            'cid' => $id
        ])->count();
        if ($num > 0)
            $str = '已经购买过了,请刷新页面';
        if ($model && $num == 0) {
            $user = User::find()->where('id=' . $uid)
                ->select('id,money')
                ->one();
            if ($user->money >= $model->price) {
                $user->money -= $model->price;
                if ($user->save([
                    'id' => $user->id,
                    'money' => $user->money
                ])) {
                    $pay = new Mclass();
                    $pay->cid = $model->id;
                    $pay->uid = $uid;
                    $pay->create_at = time();
                    if ($pay->save()) {
                        $flag = true;
                        $str = '1';
                    }
                }
            } else {
                $str = '尚好币不足请前往个人中心充值';
            }
        }
        echo json_encode([
            'status' => $str
        ]);
    }

    /**
     * Finds the Course model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * 
     * @param string $id            
     * @return Course the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Course::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
